<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import InputError from '@/Components/InputError.vue';
import NestedReply from '@/Components/NestedReply.vue';
import Toast from '@/Components/Toast.vue';
import { Head, Link, useForm, router, usePage } from '@inertiajs/vue3';
import { computed, ref, nextTick, watch } from 'vue';

const props = defineProps({
    post: Object,
    isLiked: Boolean,
    isFavorited: Boolean,
    replies: Object,
    flash: Object,
});

const likeForm = useForm({});
const favoriteForm = useForm({});

// Toast 通知状态
const toastMessage = ref(null);
const toastType = ref('info');
const showToast = ref(false);

// 显示 Toast 通知
const showToastMessage = (message, type = 'info') => {
    toastMessage.value = message;
    toastType.value = type;
    showToast.value = true;
    // 3秒后自动关闭
    setTimeout(() => {
        showToast.value = false;
    }, 3000);
};

// 回复表单
const replyForm = useForm({
    content: '',
    parent_id: null,
});

// 当前回复的父ID（用于楼中楼回复）
const replyingTo = ref(null);

// 回复元素的 refs（用于滚动定位）
const replyRefs = ref({});

const startReply = async (parentId = null) => {
    replyingTo.value = parentId;
    replyForm.parent_id = parentId;
    replyForm.content = '';
    
    // 滚动到回复框位置（等待 DOM 更新）
    if (parentId) {
        // 使用 nextTick 确保 DOM 更新后再滚动
        await nextTick();
        
        // 再次等待，确保回复框已渲染
        await nextTick();
        
        const replyElement = replyRefs.value[parentId];
        if (replyElement) {
            // 查找回复框元素，优先滚动到回复框
            const formElement = replyElement.querySelector('form');
            const targetElement = formElement || replyElement;
            targetElement.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
        }
    }
};

const cancelReply = () => {
    replyingTo.value = null;
    replyForm.parent_id = null;
    replyForm.content = '';
};

const submitReply = () => {
    replyForm.post(route('replies.store', props.post.slug), {
        preserveScroll: true,
        onSuccess: () => {
            replyForm.reset();
            replyingTo.value = null;
            router.reload({ only: ['replies', 'post'] });
        },
    });
};

// 回复点赞
const replyLikeForms = ref({});

const handleReplyLike = (reply) => {
    if (!replyLikeForms.value[reply.id]) {
        replyLikeForms.value[reply.id] = useForm({});
    }
    replyLikeForms.value[reply.id].post(route('replies.like', reply.id), {
        preserveScroll: true,
        onSuccess: () => {
            router.reload({ only: ['replies'] });
        },
    });
};

// 删除回复
const deleteReplyForm = ref({});

const handleDeleteReply = (reply) => {
    if (!confirm('确定要删除这条回复吗？')) {
        return;
    }
    if (!deleteReplyForm.value[reply.id]) {
        deleteReplyForm.value[reply.id] = useForm({});
    }
    deleteReplyForm.value[reply.id].delete(route('replies.destroy', reply.id), {
        preserveScroll: true,
        onSuccess: () => {
            router.reload({ only: ['replies', 'post'] });
        },
    });
};

// 举报功能
const reportModalVisible = ref(false);
const reportType = ref(null);
const reportId = ref(null);
const reportForm = useForm({
    reason: '',
    description: '',
});

const showReportModal = (type, id) => {
    reportType.value = type;
    reportId.value = id;
    reportModalVisible.value = true;
    reportForm.reset();
};

const closeReportModal = () => {
    reportModalVisible.value = false;
    reportForm.reset();
};

const submitReport = () => {
    // 将 type 和 id 添加到表单数据中
    reportForm.transform((data) => ({
        ...data,
        type: reportType.value,
        id: reportId.value,
    })).post(route('reports.store'), {
        preserveScroll: true,
        onSuccess: () => {
            closeReportModal();
            // 成功消息会通过 flash 显示
        },
        onError: (errors) => {
            console.error('举报提交错误:', errors);
        },
    });
};

// 监听 flash 消息
watch(() => props.flash?.success, (success) => {
    if (success) {
        showToastMessage(success, 'success');
    }
});

watch(() => props.flash?.error, (error) => {
    if (error) {
        showToastMessage(error, 'error');
    }
});

const handleLike = () => {
    likeForm.post(route('posts.like', props.post.slug), {
        preserveScroll: true,
    });
};

const handleFavorite = () => {
    favoriteForm.post(route('posts.favorite', props.post.slug), {
        preserveScroll: true,
    });
};

const getUserAvatar = (user) => {
    if (user?.avatar) {
        return user.avatar.startsWith('http') ? user.avatar : `/storage/${user.avatar}`;
    }
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user?.name || 'user'}`;
};

const getImageUrl = (image) => {
    if (!image) return null;
    return image.startsWith('http') ? image : `/storage/${image}`;
};

const formatNumber = (num) => {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
};

const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    });
};

const page = usePage();

// 判断是否为当前用户的回复
const isOwnReply = (reply) => {
    return page.props.auth?.user?.id === reply.user?.id;
};
</script>

<template>
    <Head :title="post.title" />

    <AuthenticatedLayout>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 左侧主内容 -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 帖子内容卡片 -->
                <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <!-- 作者信息 -->
                        <div class="flex items-center gap-3 mb-4">
                            <Link
                                v-if="post.user"
                                :href="route('users.show', post.user?.username || post.user?.id)"
                                class="hover:opacity-80 transition-opacity"
                            >
                                <img
                                    :src="getUserAvatar(post.user)"
                                    :alt="post.user?.nickname || post.user?.name"
                                    class="w-12 h-12 rounded-full"
                                />
                            </Link>
                            <img
                                v-else
                                src="https://api.dicebear.com/7.x/avataaars/svg?seed=anonymous"
                                alt="匿名用户"
                                class="w-12 h-12 rounded-full"
                            />
                            <div>
                                <Link
                                    v-if="post.user"
                                    :href="route('users.show', post.user?.username || post.user?.id)"
                                    class="font-semibold hover:opacity-80 transition-opacity block"
                                >
                                    {{ post.user?.nickname || post.user?.name }}
                                </Link>
                                <span v-else class="font-semibold">匿名用户</span>
                                <div class="text-sm text-muted-foreground">{{ formatTime(post.created_at) }}</div>
                            </div>
                        </div>

                        <!-- 帖子标题和内容 -->
                        <h1 class="text-3xl font-bold mb-4">{{ post.title }}</h1>
                        <div class="prose max-w-none mb-6">
                            <div class="whitespace-pre-wrap text-lg leading-relaxed">{{ post.content }}</div>
                        </div>

                        <!-- 帖子图片 -->
                        <div v-if="post.images && post.images.length" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
                            <img
                                v-for="(image, index) in post.images"
                                :key="index"
                                :src="getImageUrl(image)"
                                :alt="`图片 ${index + 1}`"
                                class="w-full rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity"
                            />
                        </div>
                    </div>

                    <!-- 帖子操作栏 -->
                    <div class="px-6 pt-4 border-t">
                        <div class="flex items-center gap-6">
                            <button
                                v-if="$page.props.auth?.user"
                                @click="handleLike"
                                :disabled="likeForm.processing"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
                                :class="isLiked ? 'text-red-500' : ''"
                            >
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
                                </svg>
                                {{ formatNumber(post.like_count) }}
                            </button>
                            <button
                                v-if="$page.props.auth?.user"
                                @click="handleFavorite"
                                :disabled="favoriteForm.processing"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
                                :class="isFavorited ? 'text-yellow-500' : ''"
                            >
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                                </svg>
                                {{ formatNumber(post.reply_count || 0) }}
                            </button>
                            <button class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2">
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                                </svg>
                                分享
                            </button>
                            <button
                                v-if="$page.props.auth?.user"
                                @click="handleFavorite"
                                :disabled="favoriteForm.processing"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 ml-auto"
                                :class="isFavorited ? 'text-yellow-500' : ''"
                            >
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
                                </svg>
                            </button>
                            <button
                                v-if="$page.props.auth?.user && post.user && post.user.id !== $page.props.auth.user.id"
                                @click="showReportModal('post', post.id)"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 ml-auto text-muted-foreground"
                            >
                                <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                </svg>
                                举报
                            </button>
                            <div v-if="post.user && $page.props.auth?.user && post.user.id === $page.props.auth.user.id" class="ml-auto">
                                <Link :href="route('posts.edit', post.slug)" class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2">
                                    编辑
                                </Link>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 回复区域 -->
                <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <h2 class="text-xl font-bold mb-4">评论 ({{ formatNumber(post.reply_count || 0) }})</h2>
                        
                        <!-- 回复表单（仅在没有回复特定评论时显示） -->
                        <div v-if="$page.props.auth?.user && !replyingTo" class="mb-6">
                            <form @submit.prevent="submitReply">
                                <textarea
                                    v-model="replyForm.content"
                                    placeholder="写下你的评论..."
                                    rows="4"
                                    class="w-full px-3 py-2 border border-input rounded-md bg-transparent text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 resize-none"
                                    required
                                ></textarea>
                                <InputError class="mt-2" :message="replyForm.errors.content" />
                                <InputError class="mt-2" :message="replyForm.errors.parent_id" />
                                <div class="flex items-center justify-end gap-2 mt-3">
                                    <PrimaryButton :disabled="replyForm.processing">
                                        发布评论
                                    </PrimaryButton>
                                </div>
                            </form>
                        </div>

                        <!-- 未登录提示（只在真正未登录时显示） -->
                        <div v-else-if="!$page.props.auth?.user" class="mb-6 p-4 bg-muted rounded-lg text-center text-muted-foreground">
                            <p>请先 <Link :href="route('login')" class="text-primary hover:underline">登录</Link> 后发表评论</p>
                        </div>

                        <!-- 回复列表 -->
                        <div v-if="replies && replies.data && replies.data.length > 0" class="space-y-4">
                            <div
                                v-for="(reply, index) in replies.data"
                                :key="reply.id"
                                :ref="el => { if (el) replyRefs[reply.id] = el }"
                                class="pb-4 border-b last:border-b-0"
                            >
                                <!-- 主回复 -->
                                <div class="flex gap-3">
                                    <Link
                                        :href="route('users.show', reply.user?.username || reply.user?.id)"
                                        class="flex-shrink-0"
                                    >
                                        <img
                                            :src="getUserAvatar(reply.user)"
                                            :alt="reply.user?.nickname || reply.user?.name"
                                            class="w-8 h-8 rounded-full"
                                        />
                                    </Link>
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-center justify-between mb-1">
                                            <div class="flex items-center gap-2">
                                                <Link
                                                    :href="route('users.show', reply.user?.username || reply.user?.id)"
                                                    class="text-base font-medium text-foreground hover:underline"
                                                >
                                                    {{ reply.user?.nickname || reply.user?.name }}
                                                </Link>
                                                <span class="text-sm text-muted-foreground">
                                                    {{ formatTime(reply.created_at) }}
                                                </span>
                                            </div>
                                            <div class="flex items-center gap-2 text-sm text-muted-foreground">
                                                <button
                                                    v-if="$page.props.auth?.user"
                                                    @click="startReply(reply.id)"
                                                    class="hover:text-foreground transition-colors"
                                                >
                                                    回复
                                                </button>
                                                <button
                                                    v-if="$page.props.auth?.user && !isOwnReply(reply)"
                                                    @click="showReportModal('reply', reply.id)"
                                                    class="hover:text-foreground transition-colors"
                                                >
                                                    举报
                                                </button>
                                                <button
                                                    v-if="isOwnReply(reply)"
                                                    @click="handleDeleteReply(reply)"
                                                    :disabled="deleteReplyForm[reply.id]?.processing"
                                                    class="text-red-500 hover:text-red-700 transition-colors"
                                                >
                                                    删除
                                                </button>
                                            </div>
                                        </div>
                                        <p class="text-base text-foreground whitespace-pre-wrap leading-relaxed">{{ reply.content }}</p>

                                        <!-- 该评论的回复框（动态显示） -->
                                        <div v-if="replyingTo === reply.id && $page.props.auth?.user" class="mt-3 pt-3 border-t">
                                            <form @submit.prevent="submitReply">
                                                <textarea
                                                    v-model="replyForm.content"
                                                    placeholder="回复这条评论..."
                                                    rows="3"
                                                    class="w-full px-3 py-2 border border-input rounded-md bg-transparent text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 resize-none"
                                                    required
                                                    autofocus
                                                ></textarea>
                                                <InputError class="mt-2" :message="replyForm.errors.content" />
                                                <InputError class="mt-2" :message="replyForm.errors.parent_id" />
                                                <div class="flex items-center justify-end gap-2 mt-2">
                                                    <button
                                                        type="button"
                                                        @click="cancelReply"
                                                        class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-8 px-3 py-1 text-xs"
                                                    >
                                                        取消
                                                    </button>
                                                    <PrimaryButton :disabled="replyForm.processing" class="h-8 px-3 py-1 text-xs">
                                                        回复
                                                    </PrimaryButton>
                                                </div>
                                            </form>
                                        </div>

                                        <!-- 楼中楼回复（递归渲染） -->
                                        <div v-if="reply.children && reply.children.length > 0" class="mt-3">
                                            <NestedReply
                                                v-for="child in reply.children"
                                                :key="child.id"
                                                :reply="child"
                                                :depth="1"
                                                :replying-to="replyingTo"
                                                :reply-content="replyForm.content"
                                                :reply-ref="(id, el) => { if (el) replyRefs[id] = el }"
                                                @reply="startReply"
                                                @like="handleReplyLike"
                                                @delete="handleDeleteReply"
                                                @report="(id) => showReportModal('reply', id)"
                                                @submit-reply="submitReply"
                                                @cancel-reply="cancelReply"
                                                @update:reply-content="(value) => replyForm.content = value"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 分页 -->
                            <div v-if="replies.links && replies.links.length > 3" class="flex items-center justify-center gap-2 pt-4">
                                <Link
                                    v-for="(link, index) in replies.links"
                                    :key="index"
                                    :href="link.url || '#'"
                                    v-html="link.label"
                                    :class="[
                                        'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2',
                                        link.active ? 'bg-primary text-primary-foreground shadow-sm' : 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
                                        !link.url ? 'text-muted-foreground cursor-not-allowed opacity-50' : ''
                                    ]"
                                />
                            </div>
                        </div>

                        <!-- 空状态 -->
                        <div v-else class="text-center py-12 text-muted-foreground">
                            <p>暂无评论，快来抢沙发吧~</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧边栏 -->
            <div class="space-y-6">
                <!-- 贴吧信息卡片 -->
                <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                    <div class="px-6">
                        <Link :href="route('bars.show', post.bar?.slug)" class="flex items-center gap-3 mb-4 hover:opacity-80 transition-opacity">
                            <img
                                :src="post.bar?.avatar || `https://api.dicebear.com/7.x/shapes/svg?seed=${post.bar?.name}`"
                                :alt="post.bar?.name"
                                class="w-12 h-12 rounded-lg"
                            />
                            <div>
                                <div class="font-semibold">{{ post.bar?.name }}</div>
                                <div class="text-sm text-muted-foreground">{{ formatNumber(post.bar?.member_count || 0) }} 成员</div>
                            </div>
                        </Link>
                        <Link
                            :href="route('bars.show', post.bar?.slug)"
                            class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 w-full"
                        >
                            进入贴吧
                        </Link>
                    </div>
                </div>
            </div>
        </div>

        <!-- 举报模态框 -->
        <div v-if="reportModalVisible" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click.self="closeReportModal">
            <div class="bg-card rounded-lg border shadow-lg max-w-md w-full mx-4">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">举报内容</h3>
                        <button @click="closeReportModal" class="text-muted-foreground hover:text-foreground">
                            <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                    <form @submit.prevent="submitReport">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium mb-2">举报原因</label>
                                <select
                                    v-model="reportForm.reason"
                                    class="w-full px-3 py-2 border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-primary"
                                    required
                                >
                                    <option value="">请选择举报原因</option>
                                    <option value="spam">垃圾信息</option>
                                    <option value="abuse">辱骂</option>
                                    <option value="inappropriate">不当内容</option>
                                    <option value="other">其他</option>
                                </select>
                                <InputError class="mt-1" :message="reportForm.errors.reason" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-2">详细描述（选填）</label>
                                <textarea
                                    v-model="reportForm.description"
                                    rows="4"
                                    placeholder="请描述具体原因..."
                                    class="w-full px-3 py-2 border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-primary resize-none"
                                    maxlength="500"
                                ></textarea>
                                <InputError class="mt-1" :message="reportForm.errors.description" />
                            </div>
                        </div>
                        <div class="flex items-center justify-end gap-3 mt-6">
                            <button
                                type="button"
                                @click="closeReportModal"
                                class="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
                            >
                                取消
                            </button>
                            <PrimaryButton :disabled="reportForm.processing">
                                提交举报
                            </PrimaryButton>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Toast 通知 -->
        <Toast
            v-if="showToast"
            :type="toastType"
            :message="toastMessage"
            @close="showToast = false"
        />
    </AuthenticatedLayout>
</template>

